﻿#include "Download.h"

Download::Download(QObject *parent) :
    QObject(parent)
{
    m_fileType = 0;
    m_file = NULL;
    m_http = new QNetworkAccessManager(this);
}

void Download::setParam(const PortStruct &source, const quint8 &fileType, const QString &url, const QByteArray &sha, const QString &path)
{
    this->m_fileType = fileType;
    this->m_url = url;
    this->m_sha = sha;
    this->m_source = source;

    int index = url.indexOf("fileName=") + 9;
    this->m_fileName = url.mid(index);
//    m_fileName = "update.zip";

    QDir dir(path);
    if(!dir.exists())
    {
        dir.mkdir(path);
    }

    this->m_path = path + "/" + this->m_fileName;

}

void Download::start()
{
    if(m_file != NULL)
    {
        return;
    }

    qDebug()<<"Download file starts!";
    m_file = new QFile(this->m_path);
    if(!m_file->open(QIODevice::ReadWrite))
    {
        delete m_file;
        m_file = NULL;
        emit downloadFinishedSignal(m_source,false,this->m_fileType,this->m_path);
        return;
    }

    m_reply = m_http->get(QNetworkRequest(QUrl(this->m_url)));
    connect(m_reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(m_reply, SIGNAL(finished()),  this, SLOT(finishedSlot()));
}

void Download::readyReadSlot()
{
    if(m_file != NULL)
    {
        m_file->write(m_reply->readAll());
    }
    qDebug()<<"Donwloading....";
}

void Download::finishedSlot()
{
    if(m_file != NULL)
    {
        m_file->close();
        if(!m_file->open(QIODevice::ReadOnly))
        {
            qDebug()<<"File download failed:The file cannot be opened!";
            emit downloadFinishedSignal(m_source,false,this->m_fileType,this->m_path);
        }
        else
        {
            QByteArray fileArray = m_file->readAll();
            m_file->close();
            quint64 size = fileArray.size();
            unsigned char* strfile = (unsigned char*) fileArray.data();
            unsigned char* strSHA1 = (unsigned char*)malloc(20);
            memset(strSHA1,0,20);
            SHA1(strfile, size, strSHA1);
            QByteArray sha((char *)strSHA1,20);

            if(sha == this->m_sha)
            {
                qDebug()<<"File download succeed!";
                emit downloadFinishedSignal(m_source,true,this->m_fileType,this->m_path);
            }
            else
            {
                qDebug()<<"File download failed:The file validation error!";
                emit downloadFinishedSignal(m_source,false,this->m_fileType,this->m_path);
            }
        }
        m_reply->disconnect();
        delete m_file;
        m_file = NULL;
    }
}
